## encoding = "utf-8"

import os
import config
# from flask_migrate import Migrate
from srf_log import init_log
import global_var
from cal_func.ids_change_interval import get_industry_change, get_industry_plot
from cal_func.ids_stock_changge_pct import indus_stock_changpct, ids_stock_change_plot
from smart_chance.find_grow_chance import stock_roe_rank
from public_func.last_date import ids_name_last_date
import traceback



from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)


@app.route('/industry_name_date', methods=['POST'])
def industry_code_name_date():
    ids_code = request.json.get('code', "")
    data = ids_name_last_date(code=ids_code)
    return data



@app.route('/industry_change_pct', methods=['POST'])
def industry_price_change_pct():
    change = get_industry_change()
    data = {
        "data": change
    }

    return data


@app.route('/industry_change_plot', methods=['POST'])
def industry_price_change_plot():
    industry_code = request.json.get('industry_code', 'BK0459')  # 默认值
    change = get_industry_plot(ids=industry_code)
    data = {
        "data": change
    }

    return data



@app.route('/ids_stock_change_pct', methods=['POST'])
def industry_stock_change_pct():
    industry_code = request.json.get('industry_code', 'BK0459')  # 默认值
    change = indus_stock_changpct(industry_code=industry_code)
    data = {
        "data": change
    }


    return data


@app.route('/ids_stock_change_plot', methods=['POST'])
def industry_stock_change_plot():
    stock_code = request.json.get('stock', '000001')  # 默认值
    change = ids_stock_change_plot(stock=stock_code)
    data = {
        "data": change
    }

    return data



@app.route('/stock_roe_rank', methods=['POST'])
def select_stock_roe_rank():
    ## stock_code = request.json.get('stock', '000001')  # 默认值
    change = stock_roe_rank()
    print(change)
    data = {
        "data": change
    }

    return data

import subprocess
from pathlib import Path
@app.route('/daily_job_update', methods=['POST'])
def stock_data_manage():
    ## stock_code = request.json.get('stock', '000001')  # 默认值
    print("update stock data success!")
    data = {}
    try:
        current_dir = Path(__file__).parent
        parent_dir = current_dir.parent  # 上一级目录

        # 构建完整的脚本路径
        script_path = parent_dir / 'data_update.py'

        # 切换到父目录
        os.chdir(parent_dir)

        # 使用完整路径执行脚本
        command = ['python', str(script_path)]

        result = subprocess.run(
            command,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding='utf-8',  # 明确指定编码
            cwd=str(parent_dir)  # 显式指定工作目录
        )

        print("luccc")
        if result.stdout:
            print("STDOUT:", result.stdout)
        if result.stderr:
            print("STDERR:", result.stderr)
        data = {
            "data": "数据更新成功"
        }
    except subprocess.CalledProcessError as e:
        traceback.print_exc()
        print("Error occurred while trying to execute the command.")
        print(e.output)

    return data



if __name__ == '__main__':  # 无法创建database
    # 初始化日志
    global_var._init()
    global_var.init_load()
    log_path = os.path.join(config.base_dir, "./log")
    if not os.path.exists(log_path):
        os.makedirs(log_path)
    init_log(log_path, "quick_stock")
    app.run(host='0.0.0.0', port=801, debug=True)
